package com.css.fxfzypg.modules.surveytaskmanage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.cache.DivisionCache;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.manage.lethalitydifference.service.LethalityDifferenceService;
import com.css.fxfzypg.modules.group.entity.GroupEntity;
import com.css.fxfzypg.modules.group.entity.GroupUserEntity;
import com.css.fxfzypg.modules.group.entity.UserEntity;
import com.css.fxfzypg.modules.group.repository.GroupRepository;
import com.css.fxfzypg.modules.group.service.GroupUserService;
import com.css.fxfzypg.modules.group.service.impl.GroupServiceImpl;
import com.css.fxfzypg.modules.group.service.impl.GroupUserServiceimpl;
import com.css.fxfzypg.modules.maps.service.SetEarthquakeMapService;
import com.css.fxfzypg.modules.message.repository.entity.MessageEntity;
import com.css.fxfzypg.modules.message.service.MessageService;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreVo;
import com.css.fxfzypg.modules.spatialData.repository.entity.BoundaryEntity;
import com.css.fxfzypg.modules.spatialData.service.BoundaryService;
import com.css.fxfzypg.modules.surveytaskmanage.entity.FieldSurveyTaskEntity;
import com.css.fxfzypg.modules.surveytaskmanage.repository.FieldSurveyTaskRepository;
import com.css.fxfzypg.modules.surveytaskmanage.service.FieldSurveyTaskService;
import com.css.fxfzypg.modules.surveytaskmanage.vo.FieldSurveyTaskGroupVo;
import com.css.fxfzypg.modules.surveytaskmanage.vo.FieldSurveyTaskVo;
import com.css.fxfzypg.modules.surveytaskmanage.vo.FieldSurveyVo;
import com.css.fxfzypg.modules.surveytaskmanage.vo.TaskVo;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import com.css.fxfzypg.zcpt.sys.service.impl.SUserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author
 * @program
 * @description
 * @create 2022/7/26 10:30
 **/
@Service
public class FieldSurveyTaskServiceImpl implements FieldSurveyTaskService {

    @Autowired
    FieldSurveyTaskRepository fieldSurveyTaskRepository;

    @Autowired
    SUserServiceImpl sUserServiceImpl;

    @Autowired
    GroupServiceImpl groupServiceImpl;

    @Autowired
    GroupUserServiceimpl groupUserServiceimpl;

    @Autowired
    GroupUserService groupUserService;

    @Autowired
    SysAreaService sysAreaService;

    @Autowired
    GroupRepository groupRepository;

    @Autowired
    MessageService messageService;

    @Autowired
    BoundaryService boundaryService;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    LethalityDifferenceService lethalityDifferenceService;

    @Autowired
    SetEarthquakeMapService setEarthquakeMapService;//地图使用

    @Autowired
    SUserService sUserService;

    /**
     * 新建任务
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveTask(FieldSurveyTaskVo fieldSurveyTaskVo) throws UnsupportedEncodingException {
        FieldSurveyTaskEntity parentTask = fieldSurveyTaskVo.getParentTask();
        String userId = PlatformSessionContext.getUserID();
        StringBuilder taskRegion=new StringBuilder("");
        StringBuilder subTaskRegion=new StringBuilder("");
        String parentTaskId = UUIDGenerator.getUUID();
        parentTask.setDelFlag("0");
        parentTask.setCreateUser(userId);
        parentTask.setCreateTime(new Date());
        //获取用户名称
        String sUser = sUserServiceImpl.getSUser(userId);
        SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
        String userName=userInfo.getUserName();
        parentTask.setTaskManager(userName);
        parentTask.setId(parentTaskId);
        parentTask.setParentId("0");
        parentTask.setTaskManagerId(userId);

        //如果任务区域是区划选择的，通过传入的divisoncode查询任务区域
        if(!PlatformObjectUtils.isEmpty(parentTask.getRegionCodes())){
            String regionCodes = parentTask.getRegionCodes();
            String[] split = regionCodes.split(",");
            List<String> regionCodeList = Arrays.asList(split);
            for(String regionCode:regionCodeList){
                BoundaryEntity boundaryEntityByCode = boundaryService.getBoundaryEntityByCode(regionCode);
                taskRegion.append(boundaryEntityByCode.getCoordinate()+";");
            }
            parentTask.setTaskRegion(taskRegion.substring(0, taskRegion.lastIndexOf(";")));
        }
        //获取任务区域的空间数据
        parentTask.setGeom(setEarthquakeMapService.getGeomByTaskRegion(parentTask.getTaskRegion()));

        StringBuilder str=new StringBuilder();
        List<String> districtList = parentTask.getParentdistrictList();
        for(String districts:districtList){
            str.append(districts+"、");
        }
        String district=str.substring(0, str.lastIndexOf("、"));
        parentTask.setTaskDistrict(district);

        if(PlatformObjectUtils.isEmpty(parentTask.getGroupId())){
            parentTask.setTaskStatus("0");
        }else{
            parentTask.setTaskStatus("1");
            List<String> list=new ArrayList<>();

            GroupEntity groupEntity = groupRepository.selectGroup(parentTask.getGroupId());
            list.add(groupEntity.getGroupLeaderId());
            List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(parentTask.getGroupId());
            for(GroupUserEntity groupUserEntitie:groupUserEntities){
                if("0".equals(groupUserEntitie.getRole())){
                    list.add(groupUserEntitie.getUserId());
                }
            }
            for(String id:list){
                MessageEntity messageEntity=new MessageEntity();
                messageEntity.setMessageGenerator(userId);
                messageEntity.setMessageReceiver(id);
                messageEntity.setMessageContent(userName+"给您分配了 "+parentTask.getTaskName()+" 任务");
                messageService.addMessage(messageEntity);
            }
        }

        FieldSurveyTaskEntity subTask = fieldSurveyTaskVo.getSubTask();
        if(!PlatformObjectUtils.isEmpty(subTask)){
            //如果任务区域是区划选择的，通过传入的divisoncode查询任务区域
            if(!PlatformObjectUtils.isEmpty(subTask.getRegionCodes())){
                String regionCodes = subTask.getRegionCodes();
                String[] split = regionCodes.split(",");
                List<String> regionCodeList = Arrays.asList(split);
                for(String regionCode:regionCodeList){
                    BoundaryEntity boundaryEntityByCode = boundaryService.getBoundaryEntityByCode(regionCode);
                    subTaskRegion.append(boundaryEntityByCode.getCoordinate()+";");
                }
                subTask.setTaskRegion(subTaskRegion.substring(0, subTaskRegion.lastIndexOf(";")));
            }
            //获取任务区域的空间数据
            subTask.setGeom(setEarthquakeMapService.getGeomByTaskRegion(subTask.getTaskRegion()));

            StringBuilder str1=new StringBuilder();
            List<String> subTaskdistricts = subTask.getSubdistrictList();

            for(String subTaskdistrict:subTaskdistricts){
                for(String districts:districtList){
                    if(districts.contains(subTaskdistrict)){
                        str1.append(districts+"、");
                    }
                }
            }
            String subDistrict=str1.substring(0, str1.lastIndexOf("、"));
            subTask.setTaskDistrict(subDistrict);

            subTask.setDelFlag("0");
            subTask.setCreateUser(userId);
            subTask.setCreateTime(new Date());
            //获取用户名称
            subTask.setTaskManager(userName);
            subTask.setId(UUIDGenerator.getUUID());
            subTask.setParentId(parentTaskId);
            subTask.setParentTask(parentTask.getTaskNum());
            if(PlatformObjectUtils.isEmpty(subTask.getGroupId())){
                subTask.setTaskStatus("0");
            }else{
                parentTask.setTaskStatus("1");
                subTask.setTaskStatus("1");

                List<String> list=new ArrayList<>();
                GroupEntity groupEntity = groupRepository.selectGroup(subTask.getGroupId());
                list.add(groupEntity.getGroupLeaderId());
                List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(subTask.getGroupId());
                for(GroupUserEntity groupUserEntitie:groupUserEntities){
                    if("0".equals(groupUserEntitie.getRole())){
                        list.add(groupUserEntitie.getUserId());
                    }
                }
                for(String id:list){
                    MessageEntity messageEntity=new MessageEntity();
                    messageEntity.setMessageGenerator(userId);
                    messageEntity.setMessageReceiver(id);
                    if (PlatformObjectUtils.isNotEmpty(userName) && PlatformObjectUtils.isNotEmpty(parentTask.getTaskName())){
                        messageEntity.setMessageContent(userName+"给您分配了 "+subTask.getTaskName()+" 任务");
                        messageService.addMessage(messageEntity);
                    }

                }
        }
            fieldSurveyTaskRepository.saveTask(subTask);
            lethalityDifferenceService.saveDataByTask(subTask.getTaskNum(),subTask.getTaskName(), subTask.getTaskDistrict());
        }
        fieldSurveyTaskRepository.saveTask(parentTask);
        lethalityDifferenceService.saveDataByTask(parentTask.getTaskNum(),parentTask.getTaskName(), parentTask.getTaskDistrict());
        return parentTaskId;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSubTask(FieldSurveyTaskEntity subTask) throws UnsupportedEncodingException {
        StringBuilder subTaskRegion=new StringBuilder("");
        String userID = PlatformSessionContext.getUserID();
        if(!PlatformObjectUtils.isEmpty(subTask)){
            subTask.setDelFlag("0");
            subTask.setCreateUser(userID);
            subTask.setCreateTime(new Date());
            //获取用户名称PlatformSessionContext.getUserID()
            String sUser = sUserServiceImpl.getSUser(userID);
            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
            String userName=userInfo.getUserName();
            subTask.setTaskManager(userName);
            subTask.setId(UUIDGenerator.getUUID());

            //如果任务区域是区划选择的，通过传入的divisoncode查询任务区域
            if(!PlatformObjectUtils.isEmpty(subTask.getRegionCodes())){
                String regionCodes = subTask.getRegionCodes();
                String[] split = regionCodes.split(",");
                List<String> regionCodeList = Arrays.asList(split);
                for(String regionCode:regionCodeList){
                    BoundaryEntity boundaryEntityByCode = boundaryService.getBoundaryEntityByCode(regionCode);
                    subTaskRegion.append(boundaryEntityByCode.getCoordinate()+";");
                }
                subTask.setTaskRegion(subTaskRegion.substring(0, subTaskRegion.lastIndexOf(";")));
            }
            //获取任务区域的空间数据
            subTask.setGeom(setEarthquakeMapService.getGeomByTaskRegion(subTask.getTaskRegion()));

            StringBuilder str1=new StringBuilder();
            List<String> districtList = subTask.getParentdistrictList();
            List<String> subTaskdistricts = subTask.getSubdistrictList();

            for(String subTaskdistrict:subTaskdistricts){
                for(String districts:districtList){
                    if(districts.contains(subTaskdistrict)){
                        str1.append(districts+"、");
                    }
                }
            }
            String subDistrict=str1.substring(0, str1.lastIndexOf("、"));
            subTask.setTaskDistrict(subDistrict);

            if(PlatformObjectUtils.isEmpty(subTask.getGroupId())){
                subTask.setTaskStatus("0");
            }else{
                fieldSurveyTaskRepository.completeTask("1",subTask.getParentId());
                subTask.setTaskStatus("1");

                List<String> list=new ArrayList<>();
                GroupEntity groupEntity = groupRepository.selectGroup(subTask.getGroupId());
                list.add(groupEntity.getGroupLeaderId());
                List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(subTask.getGroupId());
                for(GroupUserEntity groupUserEntitie:groupUserEntities){
                    if("0".equals(groupUserEntitie.getRole())){
                        list.add(groupUserEntitie.getUserId());
                    }
                }
                for(String id:list){
                    MessageEntity messageEntity=new MessageEntity();
                    messageEntity.setMessageGenerator(userID);
                    messageEntity.setMessageReceiver(id);
                    if (PlatformObjectUtils.isNotEmpty(userName) && PlatformObjectUtils.isNotEmpty(subTask.getTaskName())){
                        messageEntity.setMessageContent(userName+"给您分配了 "+subTask.getTaskName()+" 任务");
                        messageService.addMessage(messageEntity);
                    }
                }
            }
            fieldSurveyTaskRepository.saveTask(subTask);
            lethalityDifferenceService.saveDataByTask(subTask.getTaskNum(),subTask.getTaskName(), subTask.getTaskDistrict());
        }
    }

    @Override
    public Map<String,Object> getPage(TaskVo taskVo,int curPage, int pageSize) {
        taskVo.setCreateUser(PlatformSessionContext.getUserID());
        Map<String,Object> parentTask=fieldSurveyTaskRepository.findParentIdByTask("0",taskVo,curPage,pageSize);
        List<FieldSurveyVo> tasks = (List<FieldSurveyVo>) parentTask.get("rows");
        for(FieldSurveyVo task:tasks){
            List<FieldSurveyVo> subTasks=getSubTasks(task.getId(),taskVo);
            task.setChildren(subTasks);
        }
        return parentTask;
    }

    private List<FieldSurveyVo> getSubTasks(String id,TaskVo taskVo) {
        List<FieldSurveyVo> tasks=fieldSurveyTaskRepository.findSubIdByTask(id,taskVo);
        if(tasks!=null) {
            for(FieldSurveyVo task:tasks) {
                String id1 = task.getId();
                List<FieldSurveyVo> subTask=fieldSurveyTaskRepository.findSubIdByTask(id1,taskVo);
                task.setChildren(subTask);
            }
        }
        return tasks;
    }

    @Override
    public List<FieldSurveyTaskEntity> getSubTask(String parentTaskId) {
        List<FieldSurveyTaskEntity> subTaskList =new ArrayList<>();
        if(!PlatformObjectUtils.isEmpty(parentTaskId)){
            subTaskList=fieldSurveyTaskRepository.getSubTask(parentTaskId);
            return subTaskList;
        }
        return subTaskList;
    }

    @Override
    public FieldSurveyTaskGroupVo findById(String id) {
        FieldSurveyTaskGroupVo fieldSurveyTaskGroupVo=new FieldSurveyTaskGroupVo();
        FieldSurveyTaskEntity fieldSurveyTaskEntity=fieldSurveyTaskRepository.findById(id);
        fieldSurveyTaskGroupVo.setPreAssessTaskEntity(fieldSurveyTaskEntity);
        List<UserEntity> memberList=new ArrayList<>();
        List<UserEntity> expertList=new ArrayList<>();
        List<GroupUserEntity> groupUserEntityList=groupUserService.selectGroupMemberAndGroupExpert(fieldSurveyTaskEntity.getGroupId());
        for(GroupUserEntity groupUserEntity:groupUserEntityList){
            String groupUserInfo = sUserServiceImpl.getGroupUserInfo(groupUserEntity.getUserId());
            UserEntity userInfo = CreateGson.createGson().fromJson(groupUserInfo, UserEntity.class);
            if("0".equals(groupUserEntity.getRole())){
                memberList.add(userInfo);
            }else{
                expertList.add(userInfo);
            }
        }
        fieldSurveyTaskGroupVo.setMemberlist(memberList);
        fieldSurveyTaskGroupVo.setExpertlist(expertList);
        return fieldSurveyTaskGroupVo;
    }

    @Override
    public void updateTask(FieldSurveyTaskEntity fieldSurveyTaskEntity) {
        List<String> list=new ArrayList<>();
        String groupId = fieldSurveyTaskEntity.getGroupId();
        fieldSurveyTaskEntity.setUpdateUser(PlatformSessionContext.getUserID());
        fieldSurveyTaskEntity.setUpdateTime(new Date());
        if(!PlatformObjectUtils.isEmpty(fieldSurveyTaskEntity.getGroupId())){
            fieldSurveyTaskEntity.setTaskStatus("1");
            if(!"0".equals(fieldSurveyTaskEntity.getParentId())){
                fieldSurveyTaskRepository.completeTask("1",fieldSurveyTaskEntity.getParentId());
            }
        }
        fieldSurveyTaskRepository.updateTask(fieldSurveyTaskEntity);

        if(!PlatformObjectUtils.isEmpty(groupId)){
            GroupEntity groupEntity = groupRepository.selectGroup(groupId);
            list.add(groupEntity.getGroupLeaderId());
            List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(groupId);
            for(GroupUserEntity groupUserEntitie:groupUserEntities){
                if("0".equals(groupUserEntitie.getRole())){
                    list.add(groupUserEntitie.getUserId());
                }
            }
            for(String id:list){
                MessageEntity messageEntity=new MessageEntity();
                messageEntity.setMessageGenerator(fieldSurveyTaskEntity.getCreateUser());
                messageEntity.setMessageReceiver(id);
                String sUser = sUserServiceImpl.getSUser(fieldSurveyTaskEntity.getCreateUser());
                SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
                if (PlatformObjectUtils.isNotEmpty(userInfo.getUserName()) && PlatformObjectUtils.isNotEmpty(fieldSurveyTaskEntity.getTaskName())){
                    messageEntity.setMessageContent(userInfo.getUserName()+"给您分配了 "+fieldSurveyTaskEntity.getTaskName()+" 任务");
                    messageService.addMessage(messageEntity);
                }
            }
        }
    }

    @Override
    public void completeTask(List<String> ids) {
        List<String> list=new ArrayList<>();
        List<String> subList=new ArrayList<>();
        String taskStatus="2";
        for(String id:ids){
            FieldSurveyTaskEntity task = fieldSurveyTaskRepository.findById(id);
            if("0".equals(task.getParentId())){
                fieldSurveyTaskRepository.completeTask(taskStatus,id);
                //判断是否是有子任务的父任务
                if(!PlatformObjectUtils.isEmpty(task.getGroupId())){
                    GroupEntity groupEntity = groupRepository.selectGroup(task.getGroupId());
                    list.add(groupEntity.getGroupLeaderId());
                    List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(task.getGroupId());
                    for(GroupUserEntity groupUserEntitie:groupUserEntities){
                        if("0".equals(groupUserEntitie.getRole())){
                            list.add(groupUserEntitie.getUserId());
                        }
                    }
                    for(String item:list){
                        MessageEntity messageEntity=new MessageEntity();
                        messageEntity.setMessageGenerator(task.getCreateUser());
                        messageEntity.setMessageReceiver(item);
//                        String sUser = sUserServiceImpl.getSUser(task.getCreateUser());
                        String sUser = sUserServiceImpl.getSUser(PlatformSessionContext.getUserID());
                        SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
                        messageEntity.setMessageContent(userInfo.getUserName()+"结束了 "+task.getTaskName()+" 任务");
                        messageService.addMessage(messageEntity);
                    }
                }else{
                    List<FieldSurveyTaskEntity> subTasks = fieldSurveyTaskRepository.getSubTask(task.getId());
                    for(FieldSurveyTaskEntity subTask:subTasks){
                        fieldSurveyTaskRepository.completeTask(taskStatus,subTask.getId());
                        GroupEntity subGroupEntity = groupRepository.selectGroup(subTask.getGroupId());
                        subList.add(subGroupEntity.getGroupLeaderId());
                        List<GroupUserEntity> subGroupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(subTask.getGroupId());
                        for(GroupUserEntity groupUserEntitie:subGroupUserEntities){
                            if("0".equals(groupUserEntitie.getRole())){
                                subList.add(groupUserEntitie.getUserId());
                            }
                        }
                        for(String item:subList){
                            MessageEntity messageEntity=new MessageEntity();
                            messageEntity.setMessageGenerator(task.getCreateUser());
                            messageEntity.setMessageReceiver(item);
                            String sUser = sUserServiceImpl.getSUser(task.getCreateUser());
                            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
                            messageEntity.setMessageContent(userInfo.getUserName()+"结束了 "+subTask.getTaskName()+" 任务");
                            messageService.addMessage(messageEntity);
                        }
                        subList.clear();
                    }
                }
            }else {
                FieldSurveyTaskEntity parentTask = fieldSurveyTaskRepository.findById(task.getParentId());
                fieldSurveyTaskRepository.completeTask(taskStatus,parentTask.getId());
                List<FieldSurveyTaskEntity> subTasks = fieldSurveyTaskRepository.getSubTask(parentTask.getId());
                for(FieldSurveyTaskEntity subTask:subTasks){
                    fieldSurveyTaskRepository.completeTask(taskStatus,subTask.getId());GroupEntity subGroupEntity = groupRepository.selectGroup(subTask.getGroupId());
                    subList.add(subGroupEntity.getGroupLeaderId());
                    List<GroupUserEntity> subGroupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(subTask.getGroupId());
                    for(GroupUserEntity groupUserEntitie:subGroupUserEntities){
                        if("0".equals(groupUserEntitie.getRole())){
                            subList.add(groupUserEntitie.getUserId());
                        }
                    }
                    for(String item:subList){
                        MessageEntity messageEntity=new MessageEntity();
                        messageEntity.setMessageGenerator(task.getCreateUser());
                        messageEntity.setMessageReceiver(item);
                        String sUser = sUserServiceImpl.getSUser(task.getCreateUser());
                        SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
                        messageEntity.setMessageContent(userInfo.getUserName()+"结束了 "+subTask.getTaskName()+" 任务");
                        messageService.addMessage(messageEntity);
                    }
                    subList.clear();
                }
            }

        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void assignGroup(FieldSurveyTaskEntity fieldSurveyTaskEntity) {
        List<String> list=new ArrayList<>();
        String groupId = fieldSurveyTaskEntity.getGroupId();
        fieldSurveyTaskEntity.setUpdateUser(PlatformSessionContext.getUserID());
        fieldSurveyTaskEntity.setUpdateTime(new Date());
        fieldSurveyTaskEntity.setTaskManagerId(PlatformSessionContext.getUserID());
        if(!PlatformObjectUtils.isEmpty(fieldSurveyTaskEntity.getGroupId())){
            fieldSurveyTaskEntity.setTaskStatus("1");
            if(!"0".equals(fieldSurveyTaskEntity.getParentId())){
                fieldSurveyTaskRepository.completeTask("1",fieldSurveyTaskEntity.getParentId());
            }
        }
        fieldSurveyTaskRepository.assignGroup(fieldSurveyTaskEntity);

        GroupEntity groupEntity = groupRepository.selectGroup(groupId);
        list.add(groupEntity.getGroupLeaderId());
        List<GroupUserEntity> groupUserEntities = groupUserService.selectGroupMemberAndGroupExpert(groupId);
        for(GroupUserEntity groupUserEntitie:groupUserEntities){
            if("0".equals(groupUserEntitie.getRole())){
                list.add(groupUserEntitie.getUserId());
            }
        }
        for(String id:list){
            MessageEntity messageEntity=new MessageEntity();
            messageEntity.setMessageGenerator(fieldSurveyTaskEntity.getCreateUser());
            messageEntity.setMessageReceiver(id);
            String sUser = sUserServiceImpl.getSUser(fieldSurveyTaskEntity.getCreateUser());
            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
            if (PlatformObjectUtils.isNotEmpty(userInfo.getUserName()) && PlatformObjectUtils.isNotEmpty(fieldSurveyTaskEntity.getTaskName())){
                messageEntity.setMessageContent(userInfo.getUserName()+"给您分配了 "+fieldSurveyTaskEntity.getTaskName()+" 任务");
                messageService.addMessage(messageEntity);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteTask(List<String> list) {
        for(String id:list){
            FieldSurveyTaskEntity fieldSurveyTaskEntity = fieldSurveyTaskRepository.findById(id);
            if("0".equals(fieldSurveyTaskEntity.getParentId())){
                List<FieldSurveyTaskEntity> subTaskList = fieldSurveyTaskRepository.getSubTask(fieldSurveyTaskEntity.getId());
                if(!PlatformObjectUtils.isEmpty(subTaskList)){
                    for(FieldSurveyTaskEntity subTask:subTaskList){
                        fieldSurveyTaskRepository.deleteFieldSurvey("1",subTask.getTaskNum());
                        fieldSurveyTaskRepository.deleteTask("1",subTask.getId());
                    }
                }
            }
            fieldSurveyTaskRepository.deleteFieldSurvey("1",fieldSurveyTaskEntity.getTaskNum());
            fieldSurveyTaskRepository.deleteTask("1",fieldSurveyTaskEntity.getId());
        }
    }

    @Override
    public Map<String, Object> getAppPage(HttpServletRequest request, TaskVo taskVo, int curPage, int pageSize) {
        String userId=taskVo.getUserId();
        List<GroupEntity> groupEntitys=groupServiceImpl.getGroupInfo(userId);
        List<String> grouoIds=new ArrayList<>();
        if(PlatformObjectUtils.isEmpty(groupEntitys)){
            List<GroupUserEntity> groupUserEntitys=groupUserServiceimpl.getGroupId(userId);
            for(GroupUserEntity groupUserEntity:groupUserEntitys){
                grouoIds.add(groupUserEntity.getGroupId());
            }
        }else{
            for(GroupEntity groupEntity:groupEntitys){
                grouoIds.add(groupEntity.getId());
            }
            List<GroupUserEntity> groupUserEntitys=groupUserServiceimpl.getGroupId(userId);
            for(GroupUserEntity groupUserEntity:groupUserEntitys){
                grouoIds.add(groupUserEntity.getGroupId());
            }
        }
        Map<String, Object> page = fieldSurveyTaskRepository.getAppPage(request, taskVo, curPage, pageSize,grouoIds);
        List<FieldSurveyTaskEntity> GroupEntities = (List<FieldSurveyTaskEntity>) page.get("rows");
        if(!PlatformObjectUtils.isEmpty(GroupEntities) ){
            if(!PlatformObjectUtils.isEmpty(taskVo.getLongitude()) && !PlatformObjectUtils.isEmpty(taskVo.getLatitude())){
                //标记的调研点
                Point point = new Point(new Double(taskVo.getLongitude()),new Double(taskVo.getLatitude()));
                /*point.setLocation(new Double(taskVo.getLongitude()),new Double(taskVo.getLatitude()));*/
                for(int i = 0; i < GroupEntities.size(); i++){
                    Point[] points = new Point[0];
                    FieldSurveyTaskEntity fieldSurveyTaskEntity = GroupEntities.get(i);
                    List<Point> pointList = new ArrayList<>(Arrays.asList(points));
                    String taskRegion = fieldSurveyTaskEntity.getTaskRegion();
                    if(!PlatformObjectUtils.isEmpty(taskRegion)){
                        //判断该灾害风险点是否在任务区域中
                        boolean pointInPolygon = false;
                        if (taskRegion.indexOf("MULTIPOLYGON") != -1) {//判断是否为行政区划面
                            for(String region : taskRegion.split(";")){//多个行政区划
                                region = region.substring(region.indexOf("(((") + 3, region.lastIndexOf(")))"));
                                region = region.replace(")), ((", "!");
                                region = region.replace("), (", "#");
                                if(region.contains("!")){
                                    for (String geometries : region.split("!")) {//多面
                                        if (geometries.indexOf("#") != -1) {//判断是否存在镂空的面
                                            List<String> polygonList = Arrays.asList(geometries.split("#"));
                                            for(int m=0;m<polygonList.size();m++){//是否存在镂空的面
                                                String polygon = polygonList.get(m);
                                                if(m==0){//第一个面
                                                    Point[] points1 = new Point[0];
                                                    List<Point> pointList1 = new ArrayList<>(Arrays.asList(points1));
                                                    for(String regionTemp : polygon.split(", ")){
                                                        Double regionX = new Double(regionTemp.split(" ")[0].trim());
                                                        Double regionY = new Double(regionTemp.split(" ")[1].trim());
                                                        Point regionPoint = new Point(regionX,regionY);
                                                        //regionPoint.setLocation(regionX,regionY);
                                                        pointList1.add(regionPoint);
                                                    }
                                                    //任务中选中的区域
                                                    Point[] regionPointArr = pointList1.toArray(points1);
                                                    //判断该灾害风险点是否在任务区域中
                                                    pointInPolygon = AreaBoundaryUtil.isPointInPolygon(point, regionPointArr);
                                                    if(pointInPolygon){
                                                        //继续判断是否在镂空面内
                                                        continue;
                                                    }else{
                                                        break;
                                                    }
                                                }else{//镂空的面
                                                    Point[] points1 = new Point[0];
                                                    List<Point> pointList1 = new ArrayList<>(Arrays.asList(points1));
                                                    for(String regionTemp : polygon.split(", ")){
                                                        Double regionX = new Double(regionTemp.split(" ")[0].trim());
                                                        Double regionY = new Double(regionTemp.split(" ")[1].trim());
                                                        Point regionPoint = new Point(regionX,regionY);
                                                        //regionPoint.setLocation(regionX,regionY);
                                                        pointList1.add(regionPoint);
                                                    }
                                                    //任务中选中的区域
                                                    Point[] regionPointArr = pointList1.toArray(points1);
                                                    //判断该灾害风险点是否在任务区域中
                                                    boolean tempBool = AreaBoundaryUtil.isPointInPolygon(point, regionPointArr);
                                                    if(tempBool){//判断是否在镂空面内
                                                        pointInPolygon = false;//点在镂空面内，即点不在面内
                                                    }
                                                }
                                            }

                                        }else{//正常的面
                                            Point[] points1 = new Point[0];
                                            List<Point> pointList1 = new ArrayList<>(Arrays.asList(points1));
                                            String polygon = geometries;
                                            for(String regionTemp : polygon.split(", ")){
                                                Double regionX = new Double(regionTemp.split(" ")[0].trim());
                                                Double regionY = new Double(regionTemp.split(" ")[1].trim());
                                                Point regionPoint = new Point(regionX,regionY);
                                                //regionPoint.setLocation(regionX,regionY);
                                                pointList1.add(regionPoint);
                                            }
                                            //任务中选中的区域
                                            Point[] regionPointArr = pointList1.toArray(points1);
                                            //判断该灾害风险点是否在任务区域中
                                            pointInPolygon = AreaBoundaryUtil.isPointInPolygon(point, regionPointArr);
                                            if(pointInPolygon){
                                                break;
                                            }
                                        }
                                    }
                                }else{
                                    if (region.indexOf("#") != -1) {//判断是否存在镂空的面
                                        List<String> polygonList = Arrays.asList(region.split("#"));
                                        for(int m=0;m<polygonList.size();m++){//是否存在镂空的面
                                            String polygon = polygonList.get(m);
                                            if(m==0){//第一个面
                                                Point[] points1 = new Point[0];
                                                List<Point> pointList1 = new ArrayList<>(Arrays.asList(points1));
                                                for(String regionTemp : polygon.split(", ")){
                                                    Double regionX = new Double(regionTemp.split(" ")[0].trim());
                                                    Double regionY = new Double(regionTemp.split(" ")[1].trim());
                                                    Point regionPoint = new Point(regionX,regionY);
                                                    //regionPoint.setLocation(regionX,regionY);
                                                    pointList1.add(regionPoint);
                                                }
                                                //任务中选中的区域
                                                Point[] regionPointArr = pointList1.toArray(points1);
                                                //判断该灾害风险点是否在任务区域中
                                                pointInPolygon = AreaBoundaryUtil.isPointInPolygon(point, regionPointArr);
                                                if(pointInPolygon){
                                                    //继续判断是否在镂空面内
                                                    continue;
                                                }else{
                                                    break;
                                                }
                                            }else{//镂空的面
                                                Point[] points1 = new Point[0];
                                                List<Point> pointList1 = new ArrayList<>(Arrays.asList(points1));
                                                for(String regionTemp : polygon.split(", ")){
                                                    Double regionX = new Double(regionTemp.split(" ")[0].trim());
                                                    Double regionY = new Double(regionTemp.split(" ")[1].trim());
                                                    Point regionPoint = new Point(regionX,regionY);
                                                    //regionPoint.setLocation(regionX,regionY);
                                                    pointList1.add(regionPoint);
                                                }
                                                //任务中选中的区域
                                                Point[] regionPointArr = pointList1.toArray(points1);
                                                //判断该灾害风险点是否在任务区域中
                                                boolean tempBool = AreaBoundaryUtil.isPointInPolygon(point, regionPointArr);
                                                if(tempBool){//判断是否在镂空面内
                                                    pointInPolygon = false;//点在镂空面内，即点不在面内
                                                }
                                            }
                                        }

                                    }else{//正常的面
                                        Point[] points1 = new Point[0];
                                        List<Point> pointList1 = new ArrayList<>(Arrays.asList(points1));
                                        String polygon = region;
                                        for(String regionTemp : polygon.split(", ")){
                                            Double regionX = new Double(regionTemp.split(" ")[0].trim());
                                            Double regionY = new Double(regionTemp.split(" ")[1].trim());
                                            Point regionPoint = new Point(regionX,regionY);
                                            //regionPoint.setLocation(regionX,regionY);
                                            pointList1.add(regionPoint);
                                        }
                                        //任务中选中的区域
                                        Point[] regionPointArr = pointList1.toArray(points1);
                                        //判断该灾害风险点是否在任务区域中
                                        pointInPolygon = AreaBoundaryUtil.isPointInPolygon(point, regionPointArr);
                                        if(pointInPolygon){
                                            break;
                                        }
                                    }
                                }
                                if(pointInPolygon){
                                    break;
                                }
                            }
                        }else{//地图圈选面
                            for(String region : taskRegion.split(";")){
                                Double regionX = new Double(region.split(",")[0].trim());
                                Double regionY = new Double(region.split(",")[1].trim());
                                Point regionPoint = new Point(regionX,regionY);
                                //regionPoint.setLocation(regionX,regionY);
                                pointList.add(regionPoint);
                            }
                            //任务中选中的区域
                            Point[] regionPointArr = pointList.toArray(points);
                            //判断该灾害风险点是否在任务区域中
                            pointInPolygon = AreaBoundaryUtil.isPointInPolygon(point, regionPointArr);
                        }
                        //判断该灾害风险点是否在任务区域中
                        if(pointInPolygon){
                            GroupEntities.get(i).setCurrentTask("当前任务");
                        }
                    }
                }
            }
        }
        return page;
    }

    @Override
    public String getSubTaskCode(String parentTaskNum) {
        StringBuilder stringBuilder = new StringBuilder(parentTaskNum+"-");
        String subNum="";
        DecimalFormat decimalFormat=new DecimalFormat("000");
        FieldSurveyTaskEntity parentTask=fieldSurveyTaskRepository.getParentTask(parentTaskNum);
        if(!PlatformObjectUtils.isEmpty(parentTask)){
            List<FieldSurveyTaskEntity> subTask = fieldSurveyTaskRepository.getSubTask(parentTask.getId());
            if(!PlatformObjectUtils.isEmpty(subTask)){
                String maxSubTaskCNum=fieldSurveyTaskRepository.getMaxSubTaskNum(parentTaskNum);
                String str = maxSubTaskCNum.substring(11, maxSubTaskCNum.length());
                int i = Integer.parseInt(str)+1;
                subNum=decimalFormat.format(i);
            }else{
                int i = 1;
                subNum=decimalFormat.format(i);
            }
        }else{
            int i = 1;
            subNum=decimalFormat.format(i);
        }
        return stringBuilder.append(subNum).toString();
    }


    @Override
    public String getTaskCode(String taskYear) {
        DecimalFormat decimalFormat=new DecimalFormat("000");
        String parentNum ="";
        String userId = PlatformSessionContext.getUserID();
        StringBuilder str=new StringBuilder("");
//        String user = sUserService.getSUser(userId);
//        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for(Map roleMap:roleMaps){
            str.append(roleMap.get("roleCode")+",");
        }
        String roles = str.toString();

        String divisionCode = sysAreaService.getAreaCodeByUserId(userId);
        StringBuilder code=new StringBuilder("");
        //String divisionCode = "231111";
        StringBuilder stringBuilder = new StringBuilder("D");
        if(PlatformObjectUtils.isEmpty(taskYear)){
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy");
            taskYear=sdf.format(new Date());
            stringBuilder.append(taskYear);
        }else{
            stringBuilder.append(taskYear);
        }
        //roles="88";
        divisionCode=divisionCode.substring(0,2);
        if(roles.contains(FxfzConstants.YPG_COUN_YW_ROLE) || roles.contains(FxfzConstants.YPG_COUN_GL_ROLE)){
            stringBuilder.append("00");
            code.append("00");

        }else {
            stringBuilder.append(divisionCode);
            code.append(divisionCode);
        }
        String maxParentNum=fieldSurveyTaskRepository.getMaxParentNum(taskYear,code.toString());
        if(PlatformObjectUtils.isEmpty(maxParentNum)){
            int i = 1;
            parentNum=decimalFormat.format(i);
        }else{
            String substring = maxParentNum.substring(7);
            parentNum = decimalFormat.format(Integer.parseInt(substring) + 1);
        }
        return stringBuilder.append(parentNum).toString();
    }

    @Override
    public List<Map<String, Object>> getActionTrackPersonnel(String createUser, String groupId,String taskId) {
        List<Map<String,Object>> list=new ArrayList<>();
        List<String> personnelIdList=new ArrayList<>();
        personnelIdList.add(createUser);
        if(!PlatformObjectUtils.isEmpty(groupId)){
            GroupEntity groupEntity = groupRepository.selectGroup(groupId);
            personnelIdList.add(groupEntity.getGroupLeaderId());
            List<GroupUserEntity> groupUserEntities = groupUserServiceimpl.selectGroupMemberAndGroupExpert(groupId);
            for(GroupUserEntity GroupUser:groupUserEntities){
                personnelIdList.add(GroupUser.getUserId());
            }
        }else{
            List<FieldSurveyTaskEntity> subTasks = fieldSurveyTaskRepository.getSubTask(taskId);
            if(!PlatformObjectUtils.isEmpty(subTasks)){
                for(FieldSurveyTaskEntity subTask:subTasks){
                    String subGroupId = subTask.getGroupId();
                    if(!PlatformObjectUtils.isEmpty(subGroupId)){
                        GroupEntity subGroupEntity = groupRepository.selectGroup(subGroupId);
                        personnelIdList.add(subGroupEntity.getGroupLeaderId());
                        List<GroupUserEntity> subGroupUserEntities = groupUserServiceimpl.selectGroupMemberAndGroupExpert(subGroupId);
                        for(GroupUserEntity GroupUser:subGroupUserEntities){
                            personnelIdList.add(GroupUser.getUserId());
                        }
                    }

                }
            }
        }
        List<String>  personnelIds = personnelIdList.stream().distinct().collect(Collectors.toList());
        for(String personnelId:personnelIds){
            Map<String, Object> map = new HashMap<>();
            map.put("userId",personnelId);
            //获取用户名称
            String sUser = sUserServiceImpl.getSUser(personnelId);
            SUser userInfo = CreateGson.createGson().fromJson(sUser, SUser.class);
            map.put("userName",userInfo.getUserName());
            list.add(map);
        }
        return list;
    }

    @Override
    public List<FieldSurveyTaskEntity> getParentTask() {
        String userId = PlatformSessionContext.getUserID();
        List<FieldSurveyTaskEntity> parentTask=fieldSurveyTaskRepository.getAllParentTask("0",userId);
        return parentTask;
    }

    @Override
    public List<PreVo> getFuTask() {
        List<PreVo> preVos=fieldSurveyTaskRepository.getFuTask();
        if (preVos != null && preVos.size() > 0) {
            for (PreVo preVo : preVos) {
                String taskNum = preVo.getTaskNum();
                String taskName = preVo.getTaskName();
                preVo.setTaskCodeAndTaskName(taskNum + "-" + taskName);
            }
        }
        return preVos;
    }

    @Override
    public String getGroupLeaderId(String taskNum) {
        return fieldSurveyTaskRepository.getGroupLeaderId(taskNum);
    }

    @Override
    public List<Map<String, Object>> getTeamMembers(String taskNum) {
        return fieldSurveyTaskRepository.getTeamMembers(taskNum);
    }

    @Override
    public List<TaskVo> getTask() {
        String userID = PlatformSessionContext.getUserID();
        String userJson = sUserServiceImpl.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        List<TaskVo> fieldSurveyVoList = fieldSurveyTaskRepository.getAllTask(sUser);
        //List<TaskVo> fieldSurveyVoList = fieldSurveyTaskRepository.getTask();
        if(fieldSurveyVoList!=null && fieldSurveyVoList.size()>0){
            for (TaskVo taskVo: fieldSurveyVoList) {
                String taskNum = taskVo.getTaskNum();
                String taskName = taskVo.getTaskName();
                taskVo.setTaskCodeAndTaskName(taskNum+"-"+taskName);
            }
        }
        return fieldSurveyVoList;
    }

    @Override
    public List<TaskVo> getTaskManagers() {
        return fieldSurveyTaskRepository.getTaskManagers();
    }

    @Override
    public List<Map<String, Object>> getAllTaskNum() {
        return fieldSurveyTaskRepository.getAllTaskNum();
    }

    @Override
    public String getTaskNameByTaskNum(String taskNum) {
        return fieldSurveyTaskRepository.getTaskNameByTaskNum(taskNum);
    }

    @Override
    public Boolean updateTaskIntensity(String taskId, String intensity) {
        return fieldSurveyTaskRepository.updateTaskIntensity(taskId,intensity);

    }

    @Override
    public FieldSurveyTaskEntity getById(String xcdcTaskId) {
        return fieldSurveyTaskRepository.getById(xcdcTaskId);
    }

    @Override
    public List<FieldSurveyTaskEntity> getChildrenByParentId(String id) {
        return fieldSurveyTaskRepository.getChildrenByParentId(id);
    }

    @Override
    public List<String> getGroupUserIdByTaskCode(String taskCode) {

        return fieldSurveyTaskRepository.getGroupUserIdByTaskCode(taskCode);
    }

}
